package com.yonyou.ucf.mdf.app.isvdxq.other.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.other.mapper.impl.OrgUnitMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBeanForOrg;
import com.yonyou.ucf.mdf.app.isvdxq.yonyisv.model.EventContent;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.OrgBaseEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.entity.OrgUnitEntity;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.ContentBean;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.OrgUnitBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.GenericResponse;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.PageBean;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrgUnitService {
    @Autowired
    private BaseService baseService;
    @Autowired
    private OrgUnitMapperImpl orgUnitMapper;
    @Autowired
    private OrgBaseService orgBaseService;

    public OrgUnitEntity SelectById(String id, String tenant_id) {
        return orgUnitMapper.selectById(id, tenant_id);
    }

    public List<OrgUnitEntity> SelectByIds(List<String> ids, String tenant_id) {
        return orgUnitMapper.selectByIds(ids, tenant_id);
    }

    public Boolean CheckEntity(String Id, String tenant_id) {
        int rInt = orgUnitMapper.selectCount(Id, tenant_id);
        if (rInt > 0) return true;
        else return false;
    }

    public Integer InsertEntity(OrgUnitEntity entity) {
        return orgUnitMapper.insert(entity);
    }

    public Integer UpdateEntity(OrgUnitEntity entity) {
        return orgUnitMapper.updateByPrimaryKey(entity);
    }

    public Integer DeleteById(String id) {
        return orgUnitMapper.deleteByPrimaryKey(id);
    }

    /**
     * 订阅同步数据
     * @param content
     * @throws IOException
     */
    public void AutoDataEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        JSONObject obj = JSONObject.parseObject(content.getContent());
        String jsonString = JSONObject.toJSONString(obj.get("data"));
        String detailId = JSONObject.parseObject(jsonString).get("deptId").toString();

        EventOrgUnitEdit(detailId, content.getTenantId());
    }

    /**
     * 组织单元数据加载同步
     * 订阅同步，手动拉取同步
     * @param detailId
     * @param tenantId
     * @throws IOException
     */
    public void EventOrgUnitEdit(String detailId, String tenantId) throws IOException {
        AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
        String token = MyToken.getAccessToken();
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);

        String requrl = gatewayUrl + ApiYon.getOrgunitDetail;
        Map<String, String> params = new HashMap<>();
        if (detailId.equals("")) return;
        // 除签名外的其他参数
        params.put("access_token", token);
        params.put("id", detailId);
        String resString = RequestTool.doGet(requrl, params);
        GenericResponse<OrgUnitBean> response = RequestTool.getBean(resString,
                new TypeReference<GenericResponse<OrgUnitBean>>() {
                });

        if (response.getCode().equals("200")) {
            OrgUnitBean orgUnitBean = response.getData();
            String accountOrg = "";
            //组织单元添加
            if (orgUnitBean.getAdminOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getAdminOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("adminorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                }
            }
            if (orgUnitBean.getPurchaseOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getPurchaseOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("purchaseorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                }
            }
            //库存组织
            if (orgUnitBean.getInventoryOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getInventoryOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("inventoryorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                    accountOrg = entity.getFinorgid();
                }
            }
            //会计主体
            if (orgUnitBean.getFinanceOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getFinanceOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("financeorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                    accountOrg = entity.getParentid();
                }
            }
            if (orgUnitBean.getSalesOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getSalesOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("salesorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                }
            }
            if (orgUnitBean.getQualityOrg() != null) {
                String objStr = new Gson().toJson(orgUnitBean.getQualityOrg());
                OrgBaseEntity entity = new Gson().fromJson(objStr, OrgBaseEntity.class);
                entity.setTenant_id(tenantId);
                if (!StringUtils.isEmpty(entity.getId())) {
                    entity.setOrgtype("qualityorg");
                    boolean flagNext = orgBaseService.CheckEntity(entity.getId(), entity.getOrgtype(), entity.getTenant_id());
                    if (!flagNext) orgBaseService.InsertEntity(entity);
                    else orgBaseService.UpdateEntity(entity);
                }
            }
            //实体数据处理
            if (Long.parseLong(orgUnitBean.getId()) > 0) {
                String jsonString = new Gson().toJson(orgUnitBean);
                OrgUnitEntity entity = MyTool.getBean(jsonString, OrgUnitEntity.class);
                entity.setTenant_id(tenantId);
                if (StringUtils.isEmpty(accountOrg)) {
                    accountOrg = orgUnitBean.getId();
                }
                entity.setAccountOrg(accountOrg);
                boolean flagNext = CheckEntity(entity.getId(), entity.getTenant_id());
                int rInt = 0;
                if (flagNext) {
                    rInt = UpdateEntity(entity);
                } else {
                    rInt = InsertEntity(entity);
                }
                System.out.println("EventOrgUnitEdit影响条数" + rInt);
            }
        }
    }

    /**
     * 订阅编辑未使用
     * @param content
     * @return
     * @throws IOException
     */
    public Integer EventEdit(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBean obj = RequestTool.getBean(content.getContent(), ContentBean.class);
        String jsonString = obj.getArchive().replace("detail!id", "detailid").replace("detail!", "");
        OrgUnitBean orgUnitBean = RequestTool.getBean(jsonString, OrgUnitBean.class);
        String jsonStr = new Gson().toJson(orgUnitBean);
        OrgUnitEntity orgUnitEntity = RequestTool.getBean(jsonStr, OrgUnitEntity.class);
        orgUnitEntity.setTenant_id(obj.getTenantId());
        System.out.println(JSON.toJSONString(orgUnitEntity));
        Boolean flag = CheckEntity(orgUnitEntity.getId(), obj.getTenantId());
        if (flag) {
            int rInt = UpdateEntity(orgUnitEntity);
            return rInt;
        } else {
            int rInt = InsertEntity(orgUnitEntity);
            return rInt;
        }
    }

    /**
     * 订阅实体通知删除，本地物理删除
     * @param content
     * @return
     * @throws IOException
     */
    public Integer EventDel(EventContent content) throws IOException {
        System.out.println(content.getContent());
        ContentBeanForOrg obj = RequestTool.getBean(content.getContent(), ContentBeanForOrg.class);
        String tenantId = obj.getData().getTenantId();
        if (StringUtils.isEmpty(tenantId)) tenantId = obj.getModel().getyTenantId();
        String detailId = obj.getModel().getId();
        if (StringUtils.isEmpty(detailId)) detailId = obj.getId();

        Boolean flag = CheckEntity(detailId, tenantId);
        if (flag) {
            int rInt = DeleteById(detailId);
            return rInt;
        }
        return 0;
    }

    // 同步列表数据
    public int EventItemEdit(String tenantId) throws IOException {
        String gatewayUrl = baseService.buildBusinessUrl(tenantId);
        if (StringUtils.isEmpty(gatewayUrl)) return 0;
        String requrl = gatewayUrl + ApiYon.getOrgunitSync;
        int recordCount = 0;
        int errerCount = 0;
        int curPageIndex = 0;
        boolean flagNext = true;
        while (flagNext) {
            AccessTokenResponse MyToken = baseService.getAccessToken3(tenantId);
            String token = MyToken.getAccessToken();
            Map<String, String> params = new HashMap<>();
            // 除签名外的其他参数
            params.put("access_token", token);
            params.put("pageIndex", String.valueOf(curPageIndex + 1));
            params.put("pageSize", "499");
            String resString = RequestTool.doGet(requrl, params);
            GenericResponse<PageBean<OrgUnitEntity>> response = RequestTool.getBean(resString,
                    new TypeReference<GenericResponse<PageBean<OrgUnitEntity>>>() {
                    });

            List<OrgUnitEntity> myData = new ArrayList<>();
            if (response.getCode().equals("200")) {
                int RecordCount = response.getData().getRecordCount();
                curPageIndex = response.getData().getPageIndex();
                List<OrgUnitEntity> resData = response.getData().getRecordList();
                for (OrgUnitEntity itemObj : resData) {
                    recordCount++;
                    Long tempId = Long.valueOf(StringUtils.isEmpty(itemObj.getId()) ? "0" : itemObj.getId());
                    if (tempId.longValue() > 0) {
                        String detailId = String.valueOf(itemObj.getId());
                        EventOrgUnitEdit(detailId, tenantId);
                    }
                }
                if (RecordCount <= recordCount) flagNext = false;
            } else {
                errerCount++;
            }
            if (errerCount >= 3) flagNext = false;
        }
        return recordCount;
    }
}
